<!DOCTYPE html>
<html>
<head>
    <title>Live Transcription</title>
</head>
<body>
<h1>Transcribe Audio Test</h1>
<p id="status">Connection status will go here</p>
<p id="transcript"></p>

<script>
    navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => {
        if (!MediaRecorder.isTypeSupported('audio/webm'))
            return alert('Browser not supported')

        const mediaRecorder = new MediaRecorder(stream, {
            mimeType: 'audio/webm',
        })

        const socket = new WebSocket('ws://localhost:8000/listen?uid=123&sample_rate=8000&codec=pcm8&channels=1')
        // const socket = new WebSocket('wss://josancamon19--api-fastapi-app.modal.run/listen')

        socket.onopen = () => {
            document.querySelector('#status').textContent = 'Connected'
            console.log({event: 'onopen'})
            mediaRecorder.addEventListener('dataavailable', async (event) => {
                if (event.data.size > 0 && socket.readyState == 1) {
                    socket.send(event.data)
                }
            })
            mediaRecorder.start(250)
        }

        socket.onmessage = (message) => {
            const received = message.data
            console.log('message:', received)
            if (received) {
                console.log(received)
                document.querySelector('#transcript').textContent += ' ' + received
            }
        }

        socket.onclose = () => {
            console.log({event: 'onclose'})
        }

        socket.onerror = (error) => {
            console.log({event: 'onerror', error})
        }

    })
</script>
</body>
</html>